#include "../lib/capture.hpp"
#include "../../video.hpp"
#include <boost/thread.hpp>
#include <pipc.hpp>
#include <iostream>
#include <pipc.hpp>


using namespace std;
using namespace pland;
using namespace cv;


Capture::Capture(int dev, pland::SharedDQueue qB, SharedDQueue qG, SharedDQueue qR)
{
    dev_ = dev;
    qB_ = qB;
    qG_ = qG;
    qR_ = qR;
}

Capture::~Capture()
{

}

void Capture::start()
{
    cv::VideoCapture stream1(dev_);

    if (!stream1.isOpened())
    {
        return;
    }
    stream1.set(CV_CAP_PROP_FRAME_WIDTH, 1920);
    stream1.set(CV_CAP_PROP_FRAME_HEIGHT, 1080);

    pipc::Pipc* settings = pipc::Pipc::Instance();
    pipc::Record r;
    r.data = "1920x1080";
    gettimeofday(&r.effective,NULL);
    settings->setValue("capture.resolution",r);
    pland::Data_Queue<cv::Mat> rencoder(2);
    pland::Data_Queue<cv::Mat> gencoder(2);
    pland::Data_Queue<cv::Mat> bencoder(2);
    rt_ = new boost::thread(boost::bind(&Capture::encoder, this, &rencoder,qR_));
    bt_ = new boost::thread(boost::bind(&Capture::encoder, this, &bencoder,qB_));
    gt_ = new boost::thread(boost::bind(&Capture::encoder, this, &gencoder,qG_));
    while(true)
    {
        boost::this_thread::interruption_point();
        cv::Mat cameraFrame;
        pipc::Record r = settings->getValue("motion.relarea");
        stream1.read(cameraFrame);

        Mat ChB, ChR, ChG;
        // "channels" is a vector of 3 Mat arrays:
        vector<Mat> channels(3);
        // split img:
        split(cameraFrame, channels);
        // get the channels (dont forget they follow BGR order in OpenCV)
        ChB = channels[0];
        ChG = channels[1];
        ChR = channels[2];
        rencoder.push(ChR);
        bencoder.push(ChB);
        gencoder.push(ChG);
        r = settings->getValue("motion.relarea");
        if(utill_to_int(r.data) < 4000)
            boost::this_thread::sleep(boost::posix_time::milliseconds(500));
    }
}




void Capture::encoder(pland::Data_Queue<cv::Mat> *in, pland::SharedDQueue qout)
{
    int sequence = 0;
    while(true)
    {
        boost::this_thread::interruption_point();
        cv::Mat ch = in->pop();
        struct timeval tv;
        gettimeofday(&tv, NULL);


        std::vector <uchar> png;
        cv::imencode(".png", ch, png, std::vector<int>());
        char* data = new char[png.size()];
        ::memcpy(data, png.data(), png.size());

        Data_Header *h = new Data_Header;

        h->sequenceNumber = sequence;
        h->secGlobal = tv.tv_sec;
        h->usecGlobal =  tv.tv_usec;
        h->secLocal = tv.tv_sec;
        h->usecLocal = tv.tv_usec;
        h->tag = PNG_TAG_B;
        h->size = png.size();
        SharedData item(new Data(data, h));
        qout->push(item);
        sequence++;
    }
}

void Capture::stop()
{

}
